package com.opengroupe.activity;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.opengroupe.R;
import com.opengroupe.adapter.QuestionArrayAdapter;
import com.opengroupe.dto.CandidatDto;
import com.opengroupe.dto.QuestionDto;
import com.opengroupe.dto.QuestionnaireDto;
import com.opengroupe.dto.ReponseDto;
import com.opengroupe.dto.SimpleCandidatReponsesQuestionDto;

public class QuestionActivity extends Activity {

	private ListView lvReponse;
	private TextView txtQuestion;
	private TextView txtNumQuesiton;
	private Button btnNextOrSubmit, btnPrevious;
	
	private QuestionnaireDto questionnaireDto;
	private CandidatDto candidat;
	
	private List<QuestionDto> questionDtos;
	private int currentQuestion;
	private QuestionArrayAdapter qAdapter;
	
	private String tag;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_question);
        
        tag = getString(R.string.log_prefix);

		lvReponse = (ListView) findViewById(R.id.lvReponses);
		txtQuestion = (TextView) findViewById(R.id.txtQuestion);
		txtNumQuesiton = (TextView) findViewById(R.id.txtNumQuestion);
		btnNextOrSubmit = (Button) findViewById(R.id.btnNextOrSubmit);
		btnPrevious = (Button) findViewById(R.id.btnPrevious);

		loadComponents();
		
		lvReponse.setItemsCanFocus(false);
		lvReponse.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		lvReponse.setClickable(true);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	if(currentQuestion == 1) {
	    		confirm();
	    	} else {
		    	currentQuestion -= 1;
	    		clearPreviousReponse(this);
		    	loadComponents();
		        return true;
	    	}
	    }
	    return super.onKeyDown(keyCode, event);
	}

	private OnClickListener btnNextOrSubmitListener = new OnClickListener() {
		
		public void onClick(View v) {
			
			SimpleCandidatReponsesQuestionDto scrq = new SimpleCandidatReponsesQuestionDto(candidat.getIdCandidat(),
					questionDtos.get(currentQuestion-1).getIdQuestion(), qAdapter.getSelectedIdReponses());
			
			scrq.save(getApplicationContext());
						
				if(currentQuestion < questionnaireDto.getQuestions().size()) {
					currentQuestion += 1;
					qAdapter = null;
					loadComponents();
				} else {
					Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
					intent.putExtra("caller", QuestionActivity.class.getCanonicalName());
					intent.putExtra("emailCandidat", candidat.getEmailCandidat());
					startActivityForResult(intent, 0);
					finish();
				}
			
		}
	};
	
	private OnClickListener btnPreviousListener = new OnClickListener() {
		
		public void onClick(View v) {
			if(currentQuestion == 1) {
	    		confirm();
	    		finish();
	    	} else {
		    	currentQuestion -= 1;
	    		clearPreviousReponse(getApplicationContext());
		    	loadComponents();
	    	}
		}
	};
	
	private void loadComponents() {
		if(questionnaireDto == null) {
			Bundle bundle = getIntent().getExtras();
			questionnaireDto = (QuestionnaireDto) bundle.get("questionnaire");
			
			currentQuestion = bundle.getInt("currentQuestion");
			
			questionDtos = questionnaireDto.getQuestions();
			bundle.remove("currentQuestion");
		}
		
		if(candidat == null) {
			Bundle bundle = getIntent().getExtras();
			candidat = (CandidatDto) bundle.get("candidat");			
		}

		setTitle("Questionnaire");
		
		Log.d(tag + " currentQuestion = ", Integer.toString(currentQuestion));

		txtNumQuesiton.setText(Integer.toString(currentQuestion) + ".");
		
		QuestionDto questionDto = questionDtos.get(currentQuestion-1);
		txtQuestion.setText(questionDto.getContenuQuestion().toString());
		
		List<ReponseDto> reponsesDto = questionDto.getReponses();
		
		qAdapter = new QuestionArrayAdapter(this, com.opengroupe.R.layout.lv_reponse_item, reponsesDto);
		lvReponse.setAdapter(qAdapter);
		btnNextOrSubmit.setOnClickListener(btnNextOrSubmitListener);
		btnPrevious.setOnClickListener(btnPreviousListener);
		
		if(currentQuestion == questionnaireDto.getQuestions().size()) {
			btnNextOrSubmit.setText(R.string.qSubmit);
		} else {
			btnNextOrSubmit.setText(R.string.qNext);
		}
	}
	
	private void confirm() {
		DialogInterface.OnClickListener exitListener = new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface arg0, int arg1) {
				Log.d("qRH: Arg1 : ", Integer.toString(arg1));
				if(arg1 == -1) {
					Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
					startActivityForResult(intent, 0);
					finish();
				} else {
					arg0.cancel();
				}
			}
		};
		
		Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.exit_confirm);

		builder.setMessage(R.string.exit_message);
		builder.setPositiveButton("Oui", exitListener);
		builder.setNegativeButton("Non", exitListener);
		builder.show();
	}
	
	private void clearPreviousReponse(Context context) {
		//String emailCandidat = questionnaireDto.getCandidat().getEmailCandidat();
		int idQuestion = questionDtos.get(currentQuestion - 1).getIdQuestion();
		
		SimpleCandidatReponsesQuestionDto scrq = new SimpleCandidatReponsesQuestionDto(
				candidat.getIdCandidat(), 
				idQuestion, null);
		
		scrq.delete(context);
		
		
	}
}